<?php
/**
 * @author 	Vu Nhat Lam
 * 			Mail: lamvnd@gmail.com
 * 			Mobile: 0984 52 62 68
 * @version 1.0.0
 */
// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// #################### DEFINE IMPORTANT CONSTANTS #######################
define('THIS_SCRIPT', 'bttorrents');

// ################### PRE-CACHE TEMPLATES AND DATA ######################
// get special phrase groups
$phrasegroups = array('forumdisplay', 'prefix');

// get special data templates from the datastore
$specialtemplates = array(
	'iconcache',
	'mailqueue',
	'prefixcache'
);

// ########################## REQUIRE BACK-END ############################
require_once('./global.php');
require_once(DIR . '/includes/functions_bigthree.php');
require_once(DIR . '/includes/functions_forumlist.php');
require_once(DIR . '/includes/functions_forumdisplay.php');
require_once(DIR . '/includes/functions_prefix.php');

// #######################################################################
// ######################### START MAIN SCRIPT ###########################
// #######################################################################
// draw nav bar
$navbits = array();
$navbits[fetch_seo_url('forumhome', array())] = $vbphrase['forum'];
$navbits[''] = $vbphrase['bt_top'];
$navbits = construct_navbits($navbits);
$navbar = render_navbar_template($navbits);

// Page navigation setup
$perpage = 20; // items/page
$limitlist = 100; // Fix this for top 100
$pagenumber = $vbulletin->input->clean_gpc('r', 'pagenumber', TYPE_UINT);
$sortfield = $vbulletin->input->clean_gpc('r', 'sortfield', TYPE_STR);

/////////////////////////////////
// display threads
// remove threads from users on the global ignore list
if ($Coventry = fetch_coventry('string'))
{
	$globalignore = "AND postuserid NOT IN ($Coventry) ";
}
else
{
	$globalignore = '';
}

$vbulletin->input->clean_array_gpc('r', array(
	'sortorder' => TYPE_NOHTML
));

// default sorting methods
if (empty($sortfield))
{
	$sortfield = 'thread.dateline';
}
if (empty($vbulletin->GPC['sortorder']))
{
	$vbulletin->GPC['sortorder'] = 'desc';
}

// look at sorting options:
if ('asc' != ($sortorder = $vbulletin->GPC['sortorder']))
{
	$sqlsortorder = 'DESC';
	$vbulletin->GPC['sortorder'] = 'desc';
}
else
{
	$sqlsortorder = '';
}

switch ($sortfield)
{
	case 'dateline':
		$sqlsortfield = 'thread.dateline';
		break;
	case 'seeders':
		$sqlsortfield = 'torrent.seeders';
		break;
	case 'leechers':
		$sqlsortfield = 'torrent.leechers';
		break;
	case 'completed':
		$sqlsortfield = 'torrent.completed';
		break;
	// else, use last post
	default:
		$sqlsortfield = 'thread.dateline';
		$sortfield = 'dateline';
}

$totalthreads = $limitlist;

// set defaults
sanitize_pageresults($totalthreads, $pagenumber, $perpage, 200, $vbulletin->options['maxthreads']);

$limitlower = ($pagenumber - 1) * $perpage;
$limitupper = ($pagenumber) * $perpage;

if ($limitupper > $totalthreads)
{
	$limitupper = $totalthreads;
	if ($limitlower > $totalthreads)
	{
		$limitlower = ($totalthreads - $perpage) - 1;
	}
}
if ($limitlower < 0)
{
	$limitlower = 0;
}

if ($vbulletin->options['threadpreview'] > 0)
{
	$previewfield = "post.pagetext AS preview,";
	$previewjoin = "LEFT JOIN " . TABLE_PREFIX . "post AS post ON(post.postid = thread.firstpostid)";
}
else
{
	$previewfield = '';
	$previewjoin = '';
}

if ($vbulletin->userinfo['userid'] AND in_coventry($vbulletin->userinfo['userid'], true))
{
	$tachyjoin = "
		LEFT JOIN " . TABLE_PREFIX . "tachythreadpost AS tachythreadpost ON
			(tachythreadpost.threadid = thread.threadid AND tachythreadpost.userid = " . $vbulletin->userinfo['userid'] . ")
		LEFT JOIN " . TABLE_PREFIX . "tachythreadcounter AS tachythreadcounter ON
			(tachythreadcounter.threadid = thread.threadid AND tachythreadcounter.userid = " . $vbulletin->userinfo['userid'] . ")
	";
	$tachy_columns = "
		IF(tachythreadpost.userid IS NULL, thread.lastpost, tachythreadpost.lastpost) AS lastpost,
		IF(tachythreadpost.userid IS NULL, thread.lastposter, tachythreadpost.lastposter) AS lastposter,
		IF(tachythreadpost.userid IS NULL, thread.lastposterid, tachythreadpost.lastposterid) AS lastposterid,
		IF(tachythreadpost.userid IS NULL, thread.lastpostid, tachythreadpost.lastpostid) AS lastpostid,
		IF(tachythreadcounter.userid IS NULL, thread.replycount, thread.replycount + tachythreadcounter.replycount) AS replycount,
		IF(thread.views<=IF(tachythreadcounter.userid IS NULL, thread.replycount, thread.replycount + tachythreadcounter.replycount), IF(tachythreadcounter.userid IS NULL, thread.replycount, thread.replycount + tachythreadcounter.replycount)+1, thread.views) AS views
	";
}
else
{
	$tachyjoin = '';
	$tachy_columns = 'thread.lastpost, thread.lastposter, thread.lastposterid, thread.lastpostid, thread.replycount, IF(thread.views<=thread.replycount, thread.replycount+1, thread.views) AS views';
}

$getthreadids = $db->query_read_slave("
	SELECT thread.threadid
	FROM " . TABLE_PREFIX . "post AS post
	INNER JOIN " . TABLE_PREFIX . "thread AS thread ON (thread.threadid = post.threadid)
	INNER JOIN " . TABLE_PREFIX . "attachment AS a ON (a.contentid = post.postid AND a.state = 'visible')
	INNER JOIN " . TABLE_PREFIX . "torrent AS torrent ON (torrent.torrentid = a.filedataid)
	WHERE post.visible = 1
		AND thread.visible = 1
		$globalignore
		AND a.contenttypeid = 1
	GROUP BY thread.threadid
	ORDER BY $sqlsortfield $sqlsortorder
	LIMIT $limitlower, $perpage
");

$ids = '';
while ($thread = $db->fetch_array($getthreadids))
{
	$ids .= ',' . $thread['threadid'];
}

$db->free_result($getthreadids);
unset ($thread, $getthreadids);

$threads = $db->query_read_slave("
	SELECT $previewfield
		thread.threadid, thread.title AS threadtitle, thread.forumid, pollid, open, postusername, postuserid, thread.iconid AS threadiconid,
		thread.dateline, notes, thread.visible, sticky, votetotal, thread.attach, $tachy_columns,
		thread.prefixid, thread.taglist, hiddencount, deletedcount,
		user.usergroupid, user.homepage, user.options AS useroptions, IF(userlist.friend = 'yes', 1, 0) AS isfriend
		" . (($vbulletin->options['threadsubscribed'] AND $vbulletin->userinfo['userid']) ? ", NOT ISNULL(subscribethread.subscribethreadid) AS issubscribed" : "") . "
	FROM " . TABLE_PREFIX . "thread AS thread
		LEFT JOIN " . TABLE_PREFIX . "user AS user ON (user.userid = thread.lastposterid)
		LEFT JOIN " . TABLE_PREFIX . "userlist AS userlist ON (userlist.relationid = user.userid AND userlist.type = 'buddy' AND userlist.userid = " . $vbulletin->userinfo['userid'] . ")
		" . (($vbulletin->options['threadsubscribed'] AND $vbulletin->userinfo['userid']) ?  " LEFT JOIN " . TABLE_PREFIX . "subscribethread AS subscribethread ON(subscribethread.threadid = thread.threadid AND subscribethread.userid = " . $vbulletin->userinfo['userid'] . " AND canview = 1)" : "") . "
		$previewjoin
		$tachyjoin
	WHERE thread.threadid IN (0$ids)
	ORDER BY FIELD(thread.threadid, 0$ids)
");
unset($sqlsortfield, $sqlsortorder, $threadids);

// Get Dot Threads
$dotthreads = fetch_dot_threads_array($ids);
if ($vbulletin->options['showdots'] AND $vbulletin->userinfo['userid'])
{
	$show['dotthreads'] = true;
}
else
{
	$show['dotthreads'] = false;
}

unset($ids);

$show['fetchseo'] = true;
if ($totalthreads > 0)
{
	if ($totalthreads > 0)
	{
		$limitlower++;
	}
	// check to see if there are any threads to display. If there are, do so, otherwise, show message

	if ($vbulletin->options['threadpreview'] > 0)
	{
		// Get Buddy List
		$buddy = array();
		if (trim($vbulletin->userinfo['buddylist']))
		{
			$buddylist = preg_split('/( )+/', trim($vbulletin->userinfo['buddylist']), -1, PREG_SPLIT_NO_EMPTY);
			foreach ($buddylist AS $buddyuserid)
			{
				$buddy["$buddyuserid"] = 1;
			}
		}
		DEVDEBUG('buddies: ' . implode(', ', array_keys($buddy)));
		// Get Ignore Users
		$ignore = array();
		if (trim($vbulletin->userinfo['ignorelist']))
		{
			$ignorelist = preg_split('/( )+/', trim($vbulletin->userinfo['ignorelist']), -1, PREG_SPLIT_NO_EMPTY);
			foreach ($ignorelist AS $ignoreuserid)
			{
				if (!$buddy["$ignoreuserid"])
				{
					$ignore["$ignoreuserid"] = 1;
				}
			}
		}
		DEVDEBUG('ignored users: ' . implode(', ', array_keys($ignore)));
	}

	$show['threads'] = true;
	$threadbits = '';
	$counter = 0;
	$toread = 0;

	while ($thread = $db->fetch_array($threads))
	{ // AND $counter++ < $perpage)

		// build thread data
		$thread = process_thread_array($thread);
		$forum = $vbulletin->forumcache["{$thread['forumid']}"];
		$realthreadid = $thread['realthreadid'];
		$threadbit =& $threadbits;

		($hook = vBulletinHook::fetch_hook('threadbit_display')) ? eval($hook) : false;

		// Soft Deleted Thread
		$show['moderated'] = ($thread['hiddencount'] > 0 AND can_moderate($forumid, 'canmoderateposts')) ? true : false;
		$show['deletedthread'] = ($thread['deletedcount'] > 0 AND $canseedelnotice) ? true : false;

		$pageinfo_lastpage = array();
		if ($show['pagenavmore'])
		{
			$pageinfo_lastpage['page'] = $thread['totalpages'];
		}
		$pageinfo_newpost = array('goto' => 'newpost');
		$pageinfo_lastpost = array('p' => $thread['lastpostid']);

		// prepare the member action drop-down menu
		$memberaction_dropdown = construct_memberaction_dropdown(fetch_lastposter_userinfo($thread));

		$templater = vB_Template::create('bttorrentbit');
			$templater->register('pageinfo_lastpage', $pageinfo_lastpage);
			$templater->register('pageinfo_lastpost', $pageinfo_lastpost);
			$templater->register('pageinfo_newpost', $pageinfo_newpost);
			$templater->register('subscribethread', $subscribethread);
			$templater->register('memberaction_dropdown', $memberaction_dropdown);
			$templater->register('thread', $thread);
			$templater->register('forum', $forum);
			$templater->register('threadid', $threadid);
		$threadbit .= $templater->render();
	}
	$db->free_result($threads);
	unset($thread, $counter);

	$pagenav = construct_page_nav(
		$pagenumber,
		$perpage,
		$totalthreads,
		"bttorrents.php?sort=$sortfield&order=" . $vbulletin->GPC['sortorder']
	);
}
unset($threads, $dotthreads);

construct_quick_nav();

$templater = vB_Template::create('bttorrents');
	$templater->register_page_templates();
	$templater->register('forumjump', $forumjump);
	$templater->register('navbar', $navbar);
	$templater->register('pagenav', $pagenav);
	$templater->register('threadbits', $threadbits);
	$templater->register('limitlower', $limitlower);
	$templater->register('limitupper', $limitupper);
	$templater->register('totalthreads', $totalthreads);
	$templater->register('sortfield', $sortfield);
	$templater->register('order', $vbulletin->GPC['sortorder']);
	$templater->register('pagenumber', $pagenumber);

print_output($templater->render());
